﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.Common;
using MaxLeaf.DB;
using System.Data;

namespace MaxLeaf.DAL
{
    public class GoodsInUsed
    {
        public int CheckGoodsInUsed(string strFitemID)
        {
            int iRet = 0;
            List<ServerInfo> destServers = ServerInfo.GetServers(ServerType.K3);
            string strObjectID = string.Empty;                    
            foreach (ServerInfo destServer in destServers)
            {
                using (DBAccess dbcon = new DBAccess(destServer))
                {
                    strObjectID = strFitemID;
                    iRet = CheckObjectInUsed(dbcon, strObjectID);
                    if (iRet >= 1)
                    {
                        return 1;
                    }
                }
                if (destServer.MasterDB)
                {
                    foreach (ServerInfo cityServer in ServerInfo.GetCityServers(destServer, new DBAccess(destServer).GetAllServers()))
                    {
                        //访问分账套
                        using (DBAccess dbcon = new DBAccess(cityServer))
                        {
                            KeyValuePair<string, IDataParameter[]> kvp = dbcon.CreateCondParam(new Dictionary<string, object>() { { "TableName", "t_Item" }, { "OrgKeyValue", strFitemID } });
                            string strSql = string.Format("select DestKeyValue from mkeymap where {0}", kvp.Key);

                            strObjectID = dbcon.GetValue(strSql, kvp.Value);
                            if (strObjectID.Length == 0)
                            {
                                continue;
                            }
                            
                            iRet = CheckObjectInUsed(dbcon, strObjectID);
                            if (iRet >= 1)
                            {
                                return 1;
                            }
                        }
                    }
                }
            }

            return 0;
        }

        private int CheckObjectInUsed(DBAccess dbcon, string strObjectID)
        {
            KeyValuePair<string, IDataParameter[]> kvp = dbcon.CreateCondParam(new Dictionary<string, object>() { 
                  { "type", "3" } , { "id", strObjectID } 
            });
            string strSql = @"DECLARE @return_value int

            EXEC @return_value = [dbo].[sp_ObjectInUsed]
            @ObjectType = @type,
            @ObjectID = @id

            SELECT 'Return Value' = @return_value
            ";
            string strRet = dbcon.GetValue(strSql, kvp.Value);

            return CvtFunc.ToInt(strRet);
        }
    }
}
